package fr.polichouz.geotracer.sender;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import android.net.http.AndroidHttpClient;
import fr.polichouz.geotracer.shared.Logger;
import fr.polichouz.geotracer.shared.SimpleLocation;
import fr.polichouz.geotracer.shared.SysOutErrLogger;

/**
 * Implementation of a LocationSender for Servlet.
 * 
 * @author Yoyo
 */
public class SenderForServletFactory implements SenderFactory {



    /** Singleton */
    private static SenderForServletFactory INSTANCE;

    /**
     * Get an instance of the class.
     * 
     * @param log The logger (may be null)
     * @return
     */
    public static synchronized SenderForServletFactory get(Logger log) {
	if (INSTANCE == null) {
	    INSTANCE = new SenderForServletFactory(log);
	}
	return INSTANCE;
    }

    /** Fake prototype : the object is not cloned (no need) */
    private Sender prototype;

    /** Logger */
    private Logger logger;


    /**
     * Private constructor.
     */
    private SenderForServletFactory(Logger log) {
	logger = (log == null) ? new SysOutErrLogger() : log;
	prototype = new SenderForServlet(logger);

    }

    /**
     * @see fr.polichouz.geotracer.sender.SenderFactory#make()
     */
    @Override
    public Sender make() {
	return prototype;
    }

    /**
     * Implementation of a LocationSender for servlet system.
     * 
     * @author Yoyo
     */
    private class SenderForServlet implements Sender {

	/** Web service address */
	private static final String HOST = "192.168.1.41"; // geo-tracer.appspot.com

	/** Web service service */
	private static final String SERVICE_UPDATE = "update";

	/** The user agent to use. */
	private static final String USER_AGENT = "Android HTTP Client";

	/** Logger */
	private Logger logger;

	/**
	 * Full construtor.
	 * 
	 * @param log
	 */
	SenderForServlet(Logger log) {
	    logger = log;
	}

	@Override
	public void sendAccountCreation(String username, String password) {
	    // TODO Auto-generated method stub

	}

	@Override
	public void sendUpdateLocation(final SimpleLocation location, final String username, 
		final String password) {

	    new Thread(new Runnable() {

		@Override
		public void run() {

		    logger.verbose("Sending the location ...");

		    // Construct the URL
		    StringBuilder url = new StringBuilder();
		    url.append("http://").append(HOST).append('/');
		    url.append(SERVICE_UPDATE);
		    HttpPost post = new HttpPost(url.toString());

		    // Prepare parameters
		    try {
			List<NameValuePair> p = new ArrayList<NameValuePair>();
			p.add(new BasicNameValuePair("username", username));
			p.add(new BasicNameValuePair("password", password));
			p.add(new BasicNameValuePair("lattitude", 
				location.getLattitude().toString()));
			p.add(new BasicNameValuePair("longitude", 
				location.getLongitude().toString()));
			post.setEntity(new UrlEncodedFormEntity(p));
		    } catch (UnsupportedEncodingException ex) {
		    }

		    // Send the request.
		    try {
			AndroidHttpClient.newInstance(USER_AGENT).execute(post);
		    } catch (IOException ex) {
		    }

		    logger.verbose("Location sent!");

		}
	    }).start();
	}



	@Override
	public void sendGetLocation(String username, String password) {
	    // TODO Auto-generated method stub

	}
    }
}
